<template>
	<div>
		<jk-dialog
			v-model="showDialog"
			:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-设备巡检`"
			width="1300px"
			:show-content-loading="showLoading"
			:confirm-btn-loading="saveBtnLoading"
			:show-confirm-btn="pageType !== 'detail'"
			:show-cancel-btn="pageType !== 'detail'"
			:show-close-btn="pageType === 'detail'"
			@on-close="onVisibleChange(false)"
			@on-cancel="onVisibleChange(false)"
			@on-visible-change="onVisibleChange"
			@on-confirm="onConfirmBtn"
		>
			<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1" label-width="100px" :show-message="false">
				<div ref="box1">
					<div class="flex-between-center margin-bottom-4">
						<el-tag type="primary" effect="plain">
							<span class="el-icon-tickets item-gap"></span>
							<span>基本信息</span>
						</el-tag>
						<div class="flex-end-center">
						</div>
					</div>
					<jk-card class="margin-bottom-10">
						<el-row>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="巡检单号" label-width="143px">
									<span class="read-only-2" style="width: 84%">{{ ruleForm.code }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="计划巡检人" label-width="106px">
									<span class="read-only-2" style="width: 74%">{{ ruleForm.planEmpName }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="实际巡检人" label-width="106px" prop="actualEmpName">
									<span v-if="pageType === 'detail'" class="read-only-2" style="width: 73%">{{ ruleForm.actualEmpName }}</span>
									<remoteSearchEmpInput
										v-else
										:disabled="ruleForm.serviceState === 1 || ruleForm.serviceState === 2"
										placeholder="实际巡检人"
										only-key="actualEmpCode"
										:title="`存货编码`"
										query-name="actualEmpName"
										size="medium"
										:form-data="ruleForm"
										style="width: 73%"
										@on-select="onSelectActualEmpNameChange"
									></remoteSearchEmpInput>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" style="display: flex" label="计划巡检时间(开始)" label-width="140" prop="planInspectionTime">
									<span v-if="pageType === 'detail' || ruleForm.auditState === 1" style="width: 145%" class="read-only-2 margin-left-10">{{ ruleForm.planInspectionTime }}</span>
									<jk-date-picker
										v-else
										v-model="ruleForm.planInspectionTime"
										:disabled="pageType !== 'add'"
										type="datetime"
										size="medium"
									>
									</jk-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" style="display: flex" label="实际巡检开始" label-width="140" prop="actualBeginTime">
									<span v-if="pageType === 'detail' || ruleForm.auditState === 1" style="width: 145%" class="read-only-2 margin-left-10">{{ ruleForm.actualBeginTime }}</span>
									<jk-date-picker
										v-else
										v-model="ruleForm.actualBeginTime"
										type="datetime"
										size="medium"
									>
									</jk-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" style="display: flex" label="实际结束时间" label-width="140" prop="actualEndTime">
									<span v-if="pageType === 'detail' || ruleForm.auditState === 1" style="width: 144%" class="read-only-2 margin-left-10">{{ ruleForm.actualEndTime }}</span>
									<jk-date-picker
										v-else
										v-model="ruleForm.actualEndTime"
										type="datetime"
										size="medium"
									>
									</jk-date-picker>
								</el-form-item>
							</el-col>
						</el-row>
					</jk-card>
				</div>
				<div ref="box2" style="display: flex" class="margin-bottom-4">
					<el-tag type="primary" effect="plain">
						<span class="el-icon-document item-gap"></span>
						<span>巡检明细</span>
					</el-tag>
				</div>
				<jk-table border :data="ruleForm.machineInspectionItemList" :loading="tableLoading" :height="dialogTableHeight - 50">
					<vxe-column title="设备名称" align="left" field="machineName" :width="110" />
					<vxe-column title="设备编码" align="left" field="machineCode" :width="110" />
					<vxe-column title="巡检机器状态" align="left" field="auditState" :width="170">
						<template slot-scope="scope">
							<div style="display: flex">
								<jk-select v-model="scope.row.auditState" :option-list="overStateList" :disabled="pageType === 'detail'" size="mini" placeholder="巡检机器状态" clearable></jk-select>
								<el-button v-if="(scope.row.auditState === 3 || scope.row.auditState === 4) && pageType !== 'detail'" icon="el-icon-document" size="mini" @click="onRecord(scope.row, scope.rowIndex)"></el-button>
							</div>
						</template>
					</vxe-column>
					<vxe-column title="描述问题" align="left" field="remark" :min-width="100">
						<template slot-scope="scope">
							<jk-input v-model="scope.row.remark" :disabled="pageType === 'detail'" size="mini"></jk-input>
						</template>
					</vxe-column>
					<vxe-column v-if="pageType !== 'detail'" title="操作" align="center" field="remark" :width="75">
						<template slot-scope="scope">
							<jk-button type="primary" size="mini" :has-permission="getPermission([`${prefix}:update`])" @click="onUpDataItem(scope.row)">保存</jk-button>
						</template>
					</vxe-column>
				</jk-table>
			</el-form>
		</jk-dialog>
		<addRepairRecord
			:dialog-state="showRepairRecord"
			:machine-list="machineList"
			:repair-record="true"
			:data-id="machineList.repairId"
			@on-visible-change="onVisibleChangeOfCreateDialog"
			@on-finish="onFinishOfCreateDialog"
		></addRepairRecord>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import remoteSearchProductInput from './components/remote-search-product-input/index.vue';
    import remoteSearchEmpInput from '/src/views/production/order/components/remote-search-emp-input';
    import {
        machinemanagerMachineInspectionCreate, machinemanagerMachineInspectionGet,
        machinemanagerMachineInspectionUpdate
    } from '../../../api/machine/polling';
    import {
        machinemanagerMachineInspectionItemUpdate,
        machineManagerUpkeepPersonnelPage
    } from '../../../api/machine/upkeepEmp';
    import addRepairRecord from '../repair/repairRecord/save-dialog.vue';
    import permissionMixin from '../../../mixins/permission-mixin';

    export default {
        mixins: [calHeight, permissionMixin],
        components: { remoteSearchProductInput, remoteSearchEmpInput, addRepairRecord },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                processList: [],
                prefix: 'machinemanager:machineInspectionItem',
                cottonYearTime: '',
                tableLoading: false,
                saveBtnLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                showRepairRecord: false,
                ruleForm: {
                    'actualBeginTime': '',
                    'actualEmpCode': '',
                    'actualEmpId': 0,
                    'actualEmpName': '',
                    'actualEndTime': '',
                    'auditState': 0,
                    'code': '',
                    'machineInspectionItemList': [],
                    'planEmpCode': '',
                    'planEmpId': 0,
                    'planEmpName': '',
                    'planInspectionTime': '',
                    'remark': ''
                },
                rules: {
                    actualEmpName: [{ required: true, trigger: 'change' }],
                    planInspectionTime: [{ required: true, trigger: 'change' }],
                    actualBeginTime: [{ required: true, trigger: 'change' }],
                    actualEndTime: [{ required: true, trigger: 'change' }]
                },
                overStateList: [
                    { id: 0, name: '未开始' },
                    { id: 1, name: '正常' },
                    { id: 2, name: '异常' },
                    { id: 3, name: '维修中' },
                    { id: 4, name: '维修完成' }
                ],
                recordIndex: null,
                repairRecordId: null,
                machineList: {}
            };
        },
        methods: {
            onUpDataItem(item) {
                const params = {
                    'auditState': item.auditState,
                    'id': item.id,
                    'inspectionId': item.inspectionId,
                    'machineCode': item.machineCode,
                    'machineId': item.machineId,
                    'machineName': item.machineName,
                    'processCode': '',
                    'processId': 0,
                    'processName': '',
                    'remark': item.remark,
                    'repairId': item.repairId,
                    'workshopCode': '',
                    'workshopId': 0,
                    'workshopName': ''
                };
                this.tableLoading = true;
                machinemanagerMachineInspectionItemUpdate(params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                    }
                });
            },
            onRecord(item, index) {
                this.machineList = item;
                this.recordIndex = index;
                this.showRepairRecord = true;
            },
            onVisibleChangeOfCreateDialog(e) {
                this.showRepairRecord = e;
            },
            onFinishOfCreateDialog(id) {
                if (typeof id !== 'boolean') {
                    this.$set(this.ruleForm.machineInspectionItemList[this.recordIndex], 'repairId', id);
                }
                this.showRepairRecord = false;
            },
            onSelectActualEmpNameChange(e) {
                // this.ruleForm.machineInspectionItemList = [];
                this.ruleForm.actualEmpId = e.id;
                this.ruleForm.actualEmpCode = e.code;
                this.ruleForm.actualEmpName = e.name;
                // this.getPersonnelRequest(e.id);
            },
            getPersonnelRequest(id) {
                this.tableLoading = true;
                machineManagerUpkeepPersonnelPage({ empId: id }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        this.getMachinesList(resData);
                    }
                });
            },
            getMachinesList(resData) {
                resData.forEach(itemMachine => {
                    this.ruleForm.machineInspectionItemList.push(...itemMachine.machineList);
                });
                this.tableLoading = false;
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) {
                    params.machineInspectionItemList.forEach(item => {
                        item.id = null;
                        item.createTime = '';
                    });
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? machinemanagerMachineInspectionCreate : machinemanagerMachineInspectionUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return machinemanagerMachineInspectionGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.configItem = resData.configItem || [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.processList = this.$store.state.user.userProcess.processList || [];
                if (!this.ruleForm.actualEmpName) {
                    this.$set(this.ruleForm, 'actualEmpName', this.ruleForm.planEmpName);
                    this.$set(this.ruleForm, 'actualEmpCode', this.ruleForm.planEmpCode);
                    this.$set(this.ruleForm, 'actualEmpId', this.ruleForm.planEmpId);
                }
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.$nextTick(() => {
                        this.$refs.ruleForm.clearValidate();
                    });
                    this.getDependentData();
                }
            }
        }
    };
</script>
